import {
  CallHandler,
  ExecutionContext,
  Inject,
  Injectable,
  Logger,
  NestInterceptor,
} from '@nestjs/common';
import { Observable, tap } from 'rxjs';
import { loggerProvider } from '../constants';

@Injectable()
export class RequestInterceptor implements NestInterceptor {
  constructor(@Inject(loggerProvider) private readonly logger: Logger) {}
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const start = Date.now();
    const request = context.switchToHttp().getRequest<Request>();

    const urlInfo = `${request.method} ${request.url}`;

    return next
      .handle()
      .pipe(tap(() => this.logger.log(`${urlInfo} ${Date.now() - start}ms`)));
  }
}
